<?php
class Jutuike
{
    private $apikey="";

    private $pubid="";

    public function __construct($union)
    {
        $this->apikey = $union['apikey'];
        $this->pubid = $union['pub_id'];
    }

    /**
     * 订单状态转换
     * 0    默认 1    待支付 2    已支付 3    已退款 4    已完成 5    已失效 6    已结算 11    已取消
     * 订单统一状态，0：未付款 1：已付款 2：待结算 3：已结算 4：无效订单
     */
    private $status = [
        0 => "11",
        1 => "2",
        2 => "2",
        3 => "6",
        4 => "11",
    ];


    //根据活动id返回活动名称
    public function returnAcName($ac_id){
        switch($ac_id){
            case 1://美团外卖
                $images = "https://jzcloud.jiruan.ltd/meituan_waimai.jpg";
                $tagItem = "美团外卖";
                break;
            case 42://滴滴打车
                $images = "https://yxoss-test.oss-cn-hangzhou.aliyuncs.com/cps/2022/02/25/16457664959693495";
                $tagItem = "滴滴打车";
                break;
            case 49://花小猪
                $images = "https://yxoss-test.oss-cn-hangzhou.aliyuncs.com/cps/2022/02/25/16457668118098596";
                $tagItem = "花小猪";
                break;
            case 47://高德
                $images = "https://yxoss-test.oss-cn-hangzhou.aliyuncs.com/cps/2022/02/25/16457667666424361";
                $tagItem = "高德打车";
                break;
            case 43://滴滴加油
                $images = "https://yxoss-test.oss-cn-hangzhou.aliyuncs.com/cps/2022/02/25/16457667079307303";
                $tagItem = "滴滴加油";
                break;
            case 53://滴滴代驾
                $images = "https://yxoss-test.oss-cn-hangzhou.aliyuncs.com/cps/2022/02/25/16457666841929460";
                $tagItem = "滴滴代驾";
                break;
            case 48://电费充值
                $images = "https://yxoss-test.oss-cn-hangzhou.aliyuncs.com/cps/2022/02/25/16457667265529127";
                $tagItem = "电费充值";
                break;
            case 6://话费充值
                $images = "https://yxoss-test.oss-cn-hangzhou.aliyuncs.com/cps/2022/02/25/16457668256524492";
                $tagItem = "话费充值";
                break;
            case 17://电影票在线预订
                $images = "https://yxoss-test.oss-cn-hangzhou.aliyuncs.com/cps/2022/02/25/16457667505193099";
                $tagItem = "电影票在线预订";
                break;
            case 51://电影票在线预订
                $images = "https://yxoss-test.oss-cn-hangzhou.aliyuncs.com/cps/2022/02/25/16457667505193099";
                $tagItem = "淘票票";
                break;
            case 9999://美团团购
                $images = "https://cps-oss-prod.oss-cn-hangzhou.aliyuncs.com/cps/2022/03/04/16463816685828225";
                $tagItem = "美团团购";
                break;
            case 9998://美团秒杀
                $images = "https://cps-oss-prod.oss-cn-hangzhou.aliyuncs.com/cps/2022/03/04/16463816487307076";
                $tagItem = "美团秒杀";
                break;
            default://没有匹配到，则是默认的 生活图标
                $images="https://yxoss-test.oss-cn-hangzhou.aliyuncs.com/cps/2022/02/25/16457682445425844";
                $tagItem = "本地生活";
        }
        $result['images'] = $images;
        $result['tagItem'] = $tagItem;
        return $result;
    }


    /**
     * 订单处理
     * @param $data
     * @return array
     */
    private function returnOrderDeal($data)
    {
        $responseMsgResult = [];
        foreach($data as $key=>$v1){

            if(in_array($v1['act_id'],[9])){
                continue;
            }

            $acName = $this->returnAcName($v1['act_id']);

            $turnData = [
                'orderId' => $v1['order_sn'],
                'orderStatus' => $this->status[$v1['status']],
                'orderSrc' => 11,
                'tag' => '本地生活',
                'tagItem' => $acName['tagItem'],
                'name' => $v1['order_title'],//$v1['act_name'],
                'goodsId' => '',
                'images' => $acName['images'],
                'rid' => isset($v1['sid']) && !empty($v1['sid']) ? $v1['sid'] : 0,
                'shopName' => '',
                'price' => $v1['order_price'],
                'orderType' => in_array($this->status[$v1['status']],[2,6]) ? 1 : 4,
                'payMoney' => $v1['pay_price'],
                'rebateAmount' => $v1['jtk_share_fee'],
                'incomeRate' => $v1['jtk_share_rate'],
                'orderCreateTime' => $v1['create_time'],
                'orderPaidTime' => $v1['pay_time'],
                'orderEarningTime' =>$this->status[$v1['status']]== 6 ? $v1['modified_time'] : null,
                'settleTime'  =>$this->status[$v1['status']]== 6 ? $v1['modified_time'] : null,
                'isPunish' => false,    //是否是违规订单
            ];
            $responseMsgResult[] = $turnData;
        }
        return $responseMsgResult;
    }




    /**
     * 聚推客联盟统一订单数据接口
     * https://www.jutuike.com/doc/37
     */
    public function getOrder($start_time, $end_time,$type="addOrderTime", $page = 1, &$responseMsgDataResult = [])
    {
        $url="http://api.jutuike.com/union/orders";
        $h_params['apikey'] = $this->apikey;
        $h_params['start_time'] = $start_time;
        $h_params['end_time'] = $end_time;
        $h_params['query_type'] = 3;//$type == 'addOrderTime' ? 3 : 1;
        $h_params['page'] = $page;
        $h_params['pageSize'] = 100;
        $responseMsg = \Common\Common::request_post($url,$h_params);
        if ($responseMsg['status'] && $responseMsg['data']['data']) {
            $responseMsgData = $responseMsg['data']['data'];
            if(empty($responseMsgDataResult)){
                $responseMsgDataResult = $responseMsgData['data'];
            }else{
                $responseMsgDataResult = array_merge($responseMsgDataResult, $responseMsgData['data']);
                if ($responseMsgData['last_page'] != $page) {
                    $this->getOrder($start_time, $end_time, $type, $page + 1, $responseMsgDataResult);
                }
            }
        }

//        $write       = json_encode($responseMsgDataResult);
//        $create_file = BASE_PATH."/runtime/jd.log";       //创建文件
//        file_put_contents($create_file, $write, FILE_APPEND | LOCK_EX);
        return $this->returnOrderDeal($responseMsgDataResult);
    }



    /**
     * 获取某个城市的一级类目包含的二级类目信息
     * @param $provinceId 省份ID
     * @return array
     */
    public function cityCate($cityId,$cat0Id = ''){
        $url = "http://api.act.jutuike.com/mtfx/city_categories";
        $h_params['pub_id'] = $this->pubid;
        $h_params['cityId'] = $cityId;
        if(!empty($cat0Id)){
            $h_params['cat0Id'] = $cat0Id;
        }
        $responseResult = \Common\Common::request_post($url,$h_params);
        return $responseResult['data'];
    }


    /**
     * 团单查询接口
     * @param $provinceId 省份ID
     * @return array
     */
    public function searchDeals($sid,$cat0Id,$lng,$lat,$page,$pageSize,$dealType,$sortType,$radii,$cat1Ids,$shopIds = '',$keywords = '',$del_repeat = '',$cityId=''){
        $url = "http://api.act.jutuike.com/mtfx/search_deals";
        $h_params['sid'] = 'tg'.$sid;
        $h_params['pub_id'] = $this->pubid;
        //$h_params['del_repeat'] = 2;//店铺列表去重
        $h_params['page'] = $page;
        $h_params['size'] = $pageSize;
        if(!empty($del_repeat)){
            $h_params['del_repeat'] = $del_repeat;
        }
        if(!empty($lat)){
            $h_params['lat'] = $lat;
        }
        if(!empty($lng)){
            $h_params['lng'] = $lng;
        }
        if(!empty($cat0Id)){
            $h_params['cat0Id'] = $cat0Id;
        }
        if(!empty($dealType)){
            $h_params['dealType'] = $dealType;
        }
        if(!empty($sortType)){
            $h_params['sortType'] = $sortType;
        }
        if(!empty($radii)){
            if($radii == 0 || $radii == 500 || $radii == 1000 || $radii == 3000 || $radii == 5000){
                $h_params['radii'] = $radii;
            } else {
                $h_params['regionId'] = $radii;
            }
        }
        if(!empty($cat1Ids)){
            $h_params['cat1Ids'] = $cat1Ids;
        }
        if(!empty($shopIds)){
            $h_params['shopIds'] = $shopIds;
        }
        if(!empty($keywords)){
            $h_params['keyWords'] = $keywords;
        }
        if(!empty($cityId)){
            $h_params['cityId'] = $cityId;
        }
        $responseResult = \Common\Common::request_post($url,$h_params);
        if(!empty($responseResult['data'])){
            $res = $this->turnList($responseResult['data']['records']);
        } else {
            $res = [];
        }
        return $res;
    }



    /**
     * 饿了么口碑通用返回数据
     */
    public function turnList($data){
        $responseData = [];
        foreach($data as $key=>$value){
            $temData['shopId'] = isset($value['shopInfo']['shopId']) ? $value['shopInfo']['shopId'] : "";
            $temData['title'] = isset($value['dealBaseInfo']['dealTitle']) ? $value['dealBaseInfo']['dealTitle'] : "";
            $temData['shopLogo'] = isset($value['dealBaseInfo']['defaultPic']) ? $value['dealBaseInfo']['defaultPic'] : "";
            $temData['sales'] = 0;
            $temData['itemUrl'] = isset($value['couponInfo']['couponPageUrl']) ? $value['couponInfo']['couponPageUrl'] : '';
            $temData['type'] = 2;   //1直接拉起淘宝 2调用详情接口
            $temData['deliveryPrice'] = isset($value['delivery_price']) ? $value['delivery_price'] : -1;//起送价
            $temData['deliveryFee'] = isset($value['delivery_fee']) ? $value['delivery_fee'] : -1;//配送费
            $temData['deliveryType'] = "";
            $temData['daySurplusStock'] = isset($value['activity']['daily_sellable_quantity']) ? $value['activity']['daily_sellable_quantity'] : 0;
            $temData['deliveryTime'] = isset($value['delivery_time']) ? $value['delivery_time'] : "";//配送时间
            $temData['deliveryDistance'] = isset($value['shopInfo']['distanceToShow']) ? $value['shopInfo']['distanceToShow'] : "";//距离
            $temData['serviceRating'] = isset($value['shopInfo']['shopPower']) ? $value['shopInfo']['shopPower'] : "";//评分
            $temData['salesTag'] = isset($value['couponInfo']['marketingCoupons']) && $value['couponInfo']['marketingCoupons'] && is_array($value['couponInfo']['marketingCoupons'])? array_column($value['couponInfo']['marketingCoupons'],'marketingCouponName') : [];//评分
            $temData['activityId'] = '';
            $temData['bountyMinLimitCent'] = ''; //奖励金门槛 (分)
            $temData['bonusCent'] = 0;
            $temData['recommendTips'] = isset($value['dealBaseInfo']['description']) ? $value['dealBaseInfo']['description'] : '';

            $responseData[] = $temData;
        }
        return $responseData;
    }



    /**
     * 聚推客联盟统一活动转链接口 https://www.jutuike.com/doc/48
     * @param $user_id
     * @param $activity_id
     * @return array
     */
    public function activityTurnlink($user_id,$activity_id){
        $url = "http://api.jutuike.com/union/act";
        $h_params['apikey'] = $this->apikey;
        $h_params['sid'] = $user_id;
        $h_params['act_id'] = $activity_id;
        $responseResult = \Common\Common::request_post($url,$h_params);
        if($responseResult['status']){
            if($responseResult['data']['code'] == 1) {
                $responseData = $responseResult['data']['data'];
                $result['app_url'] = isset($responseData['deeplink']) ? $responseData['deeplink'] : '';
                $result['app_id'] = isset($responseData['we_app_info']['app_id']) ? $responseData['we_app_info']['app_id'] : '';
                $result['original_id'] = isset($responseData['original_id']) ? $responseData['original_id'] : '';
                $result['page_path'] = isset($responseData['we_app_info']['page_path']) ? $responseData['we_app_info']['page_path'] : '';
                $result['wx_code'] = isset($responseData['we_app_info']['miniCode']) ? $responseData['we_app_info']['miniCode'] : '';
                $result['url'] = isset($responseData['long_h5']) ? $responseData['long_h5'] : '';
                $result['ac_name'] = isset($responseData['act_name']) ? $responseData['act_name'] : '';
                $result['short_url'] = isset($responseData['h5']) ? $responseData['h5'] : '';
                return ['status' => true, 'msg' => '获取成功', 'data' => $result];
            }else{
                return ['status'=>false,'msg'=>$responseResult['msg'],'data'=>[]];
            }
        }else{
            return ['status'=>false,'msg'=>$responseResult['msg'],'data'=>[]];
        }
    }
}